package com.example.demo.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.config.MyRequestHalper;
import com.example.demo.constant.ResponseMsg;
import com.example.demo.mapper.*;
import com.example.demo.vo.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangfc
 * @date 2021/12/17 13:42
 */
@RestController
@RequestMapping("/api")
public class buyCountController {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private MallMapper mallMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private MallOrderMapper mallOrderMapper;

    @Resource
    private UserOrderMapper userOrderMapper;

    /**
     * 获取商品列表
     *
     * @param currentPage 当前页
     * @param pageSize    每页大小
     * @return Map
     */
    @GetMapping("/listbymall/{currentPage}/{pageSize}")
    public Map<String, Object> GetAllTableData(@PathVariable("currentPage") int currentPage,
                                               @PathVariable("pageSize") int pageSize) {

        //处理当前页和每页大小的数据
        int index = (currentPage - 1) * pageSize;

        List<Mall> mallList = mallMapper.listMallByPage(index, pageSize);
        List<Map<String, Object>> tabelDataList = mallList
                .stream()
                .map((mall) -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("newdate", mall.getNewDate());
                    map.put("mallid", mall.getMallId());
                    map.put("mallname", mall.getMallName());
                    map.put("color", mall.getMallColor());
                    map.put("weight", mall.getWeight());
                    return map;
                }).collect(Collectors.toList());

        Map<String, Object> reponseMap = new HashMap<>();
        reponseMap.put("total", mallMapper.sumMall());
        reponseMap.put("currentPage", currentPage);
        reponseMap.put("pagesize", pageSize);
        reponseMap.put("tableData", tabelDataList);
        return reponseMap;
    }

    /**
     * 删除商品
     *
     * @param mallid
     * @return
     */
    @GetMapping("/delbymallid/{mallid}")
    public ResponseMsg delByMallid(@PathVariable("mallid") int mallid) {

        QueryWrapper<Mall> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mall_id", mallid);
        mallMapper.delete(queryWrapper);

        return ResponseMsg.ok();
    }

    /**
     * 保存商品
     *
     * @param jsonString json串
     * @return ResponseMsg
     */
    @PostMapping("/savemall")
    public ResponseMsg saveMall(@RequestBody String jsonString) {

        Map<String, Object> paramMap = JSONUtil.toBean(jsonString, Map.class);
        Mall mall = Mall.builder()
                .mallName(Convert.toStr(paramMap.get("newname")))
                .mallColor(Convert.toStr(paramMap.get("newcolor")))
                .newDate(Convert.toDate(paramMap.get("newdata")))
                .weight(Convert.toStr(paramMap.get("newweight"))).build();

        mallMapper.insert(mall);

        return ResponseMsg.ok();
    }

    /**
     * 获取用户列表
     *
     * @param currentPage 当前页
     * @param pageSize    每页大小
     * @return Map < String, Object>
     */
    @GetMapping("/listbyuser/{currentPage}/{pageSize}")
    public Map<String, Object> listByUser(@PathVariable("currentPage") int currentPage,
                                          @PathVariable("pageSize") int pageSize) {

        //此处为分页处理  sql limita index,page中 index 代表第index条 page代表过滤page条.
        int index = (currentPage - 1) * pageSize;
        List<UserInfo> userInfos = userInfoMapper.listByPage(index, pageSize);

        List<Map<String, Object>> tableData = userInfos.stream().map((userInfo) -> {
            String roleId = userInfo.getRoleId();
            String[] split = StrUtil.split(roleId, ",");
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("roleid", split);
            List<Role> roleList = roleMapper.selectList(queryWrapper);
            String roles = CollUtil.join(roleList
                    .stream()
                    .map((Role::getRoleName))
                    .collect(Collectors.toList()), ",");

            Map<String, Object> map = new HashMap<>();
            map.put("userid", userInfo.getUserId());
            map.put("username", userInfo.getUserName());
            map.put("name", userInfo.getName());
            map.put("gender", userInfo.getGender());
            map.put("tel", userInfo.getTel());
            map.put("birthday", DateUtil.format(userInfo.getBirthDay(),"yyyy-MM-dd HH:mm:ss"));
            map.put("email", userInfo.getEmail());
            map.put("role", roles);
            return map;
        }).collect(Collectors.toList());

        Map<String, Object> reponseMap = new HashMap<>();
        reponseMap.put("currentPage", currentPage);
        reponseMap.put("pagesize", pageSize);
        reponseMap.put("total", userInfoMapper.countByUseInfo());
        reponseMap.put("tableData", tableData);
        return reponseMap;
    }

    @GetMapping("/delbyuserid/{userid}")
    public ResponseMsg delByUserid(@PathVariable("userid") int userid) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", userid);
        userInfoMapper.delete(queryWrapper);
        return ResponseMsg.ok();
    }

    @GetMapping("/delbyroleid/{roleid}")
    public ResponseMsg delByRoleid(@PathVariable("roleid") int roleid) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roleid", roleid);
        roleMapper.delete(queryWrapper);
        return ResponseMsg.ok();
    }


    @GetMapping("/listbyorder/{currentPage}/{pageSize}")
    public Map<String, Object> listByOrder(@PathVariable("currentPage") int currentPage,
                                           @PathVariable("pageSize") int pageSize) {
        int index = (currentPage - 1) * pageSize;
        List<MyOrder> myOrders = orderMapper.listOrderByPage(index, pageSize);

        List<Map<String, Object>> tabelDataList = myOrders.stream()
                .map((myOrder) -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("orderid", myOrder.getOrderId());
                    map.put("ordernum", myOrder.getOderNum());
                    map.put("date", myOrder.getNewOrder());
                    map.put("name", myOrder.getUserName());
                    map.put("mallname", myOrder.getMallName());
                    map.put("num", myOrder.getNumber());
                    map.put("tel", myOrder.getTel());
                    map.put("address", myOrder.getMyAdress());
                    return map;
                }).collect(Collectors.toList());

        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("total", orderMapper.sumOrder());
        responseMap.put("currentPage", currentPage);
        responseMap.put("pagesize", pageSize);
        responseMap.put("tableData", tabelDataList);

        return responseMap;
    }

    /**
     * 保存商品
     *
     * @param jsonString json串
     * @return ResponseMsg
     */
    @PostMapping("/saveorder")
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseMsg saveOrder(@RequestBody String jsonString) {

        Map<String, Object> paramMap = JSONUtil.toBean(jsonString, Map.class);

        Long mallid = Convert.toLong(paramMap.get("mallid"));
        QueryWrapper<Mall> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mall_id", mallid);
        Mall mall = mallMapper.selectOne(queryWrapper);

        //生成流水号
        String orderNumber = RandomUtil.randomString(8);


        UserInfo userInfo = MyRequestHalper.getThreadLocal();
        MyOrder myOrder = MyOrder.builder()
                .mallId(mallid)
                .mallName(mall.getMallName())
                .userId(Convert.toLong(userInfo.getUserId()))
                .userName(userInfo.getUserName())
                .myAdress(Convert.toStr(paramMap.get("address")))
                .number(Convert.toLong(paramMap.get("num")))
                .newOrder(new Date())
                .tel(Convert.toStr(paramMap.get("newtel")))
                .oderNum(orderNumber).build();
        int id = orderMapper.insert(myOrder);


        //商品订单表保存
        MallOrder mallOrder = MallOrder.builder()
                .mallName(mall.getMallName())
                .mallId(Convert.toInt(myOrder.getMallId()))
                .newDate(myOrder.getNewOrder())
                .number(myOrder.getNumber())
                .orderId(id)
                .orderNum(myOrder.getOderNum())
                .build();

        mallOrderMapper.insert(mallOrder);


        UserOrder userOrder = UserOrder.builder()
                .userName(myOrder.getUserName())
                .userId(Convert.toInt(myOrder.getUserId()))
                .address(myOrder.getMyAdress())
                .newDate(myOrder.getNewOrder())
                .number(Convert.toInt(myOrder.getNumber()))
                .oderNum(myOrder.getOderNum())
                .build();

        userOrderMapper.insert(userOrder);
        return ResponseMsg.ok();
    }

    /**
     * 删除订单
     *
     * @param orderId 订单id
     * @return ResponseMsg
     */
    @GetMapping("/delbyorderid/{orderId}")
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseMsg delByOrderId(@PathVariable("orderId") int orderId) {


        QueryWrapper<MyOrder> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("order_id", orderId);


        MyOrder myOrder = orderMapper.selectOne(orderWrapper);
        orderMapper.delete(orderWrapper);


        QueryWrapper<UserOrder> usrOdrWrapper = new QueryWrapper<>();
        usrOdrWrapper.eq("oder_num", myOrder.getOderNum());
        userOrderMapper.delete(usrOdrWrapper);


        QueryWrapper<MallOrder> malOrdWrapper = new QueryWrapper<>();
        malOrdWrapper.eq("order_num", myOrder.getOderNum());
        mallOrderMapper.delete(malOrdWrapper);

        return ResponseMsg.ok();
    }

    /**
     * 获取用户订单列表
     *
     * @param currentPage 当前页
     * @param pageSize 每页大小
     * @return Map
     */
    @GetMapping("/listbyuserorder/{currentpage}/{pagesize}")
    public Map<String, Object> listByUserOrder(@PathVariable("currentpage") int currentPage,
                                               @PathVariable("pagesize") int pageSize) {
        //计算sql语句中的当前页
        int index = (currentPage - 1) * pageSize;
        List<UserOrder> userOrders = userOrderMapper.listUsrOdrByPage(index, pageSize);

        List<Map<String, Object>> tableDataList = userOrders.stream()
                .map((userOrder) -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("userorderid", userOrder.getUserorderId());
                    map.put("ordernum", userOrder.getOderNum());
                    map.put("date", userOrder.getNewDate());
                    map.put("name", userOrder.getUserName());
                    map.put("address", userOrder.getAddress());
                    map.put("number", userOrder.getNumber());
                    return map;
                }).collect(Collectors.toList());
        Map<String, Object> reponseMap = new HashMap<>();
        reponseMap.put("currentPage4", currentPage);
        reponseMap.put("pagesize", pageSize);
        reponseMap.put("total", userOrderMapper.sumTotal());
        reponseMap.put("tableData", tableDataList);
        return reponseMap;
    }

    /**
     * 获取商品订单列表
     *
     * @param currentPage 当前页
     * @param pageSize 每页大小
     * @return Map
     */
    @GetMapping("/listbymallorder/{currentPage}/{pageSize}")
    public Map<String, Object> listByMallOrder(@PathVariable("currentPage") int currentPage,
                                               @PathVariable("pageSize") int pageSize) {
        //分页计算
        int index = (currentPage - 1) * pageSize;

        List<MallOrder> mallOrderList = mallOrderMapper.listMallOrderByPage(index, pageSize);

        List<Map<String, Object>> tableDataList = mallOrderList.stream()
                .map((mallOrder) -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("mallorderid", mallOrder.getMallorderId());
                    map.put("ordernum", mallOrder.getOrderNum());
                    map.put("mallname", mallOrder.getMallName());
                    map.put("date", mallOrder.getNewDate());
                    map.put("number", mallOrder.getNumber());
                    return map;
                }).collect(Collectors.toList());

        Map<String, Object> reponseMap = new HashMap<>();

        reponseMap.put("currentPage4", currentPage);
        reponseMap.put("pagesize", pageSize);
        reponseMap.put("total", mallOrderMapper.sumTotal());
        reponseMap.put("tableData", tableDataList);
        return reponseMap;
    }
}
